<template>
  <main class="file-list-container">
    <div class="file-form">
      <el-form :model="fileForm" label-width="46px">
        <el-form-item label="名称">
          <el-input v-model="fileForm.name" placeholder="请输入关键字检索" style="width: 270px" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="fileForm.status" placeholder="请选择状态" style="width: 270px" clearable>
            <el-option v-for="item in statusArray" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="file-operations">
      <el-button @click="handleUploadFile" type="primary" style="width: 92px"
        ><el-icon style="padding-right: 8px"><Plus /></el-icon>选择文件</el-button
      >
      <el-button type="primary" plain style="width: 72px">全部开始</el-button>
      <el-button type="danger" plain style="width: 72px">全部停止</el-button>
      <input type="file" ref="fileInput" @change="handleFileInputChange" :multiple="true" style="display: none" />
    </div>
    <div class="file-table">
      <el-table ref="multipleTableRef" :data="dataSource" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="日期" width="170">
          <template #default="scope">{{
            scope.row.date ? dayjs(scope.row.date).format('YYYY/MM/DD HH:mm:ss') : ''
          }}</template>
        </el-table-column>
        <el-table-column property="name" label="文件名称">
          <template #default="scope">
            <span class="file-name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column property="status" label="状态" width="113" align="center">
          <template #default="scope">
            <el-tag :type="(mapStatus.get(scope.row.status) || {type: undefined}).type">{{
              (mapStatus.get(scope.row.status) || {}).text
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="progress" label="完成进度" width="200">
          <template #default="scope"><el-progress :percentage="scope.row.progress" /> </template>
        </el-table-column>
        <el-table-column label="操作" width="132">
          <template #default>
            <el-space :size="8" spacer="">
              <el-text size="small" type="primary">查看</el-text>
              <el-text size="small" type="primary">停止</el-text>
              <!-- <el-text>开始</el-text>
                <el-text>重传</el-text> -->
              <el-text size="small" type="primary">删除</el-text>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <div class="file-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 30]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import {ref, computed} from 'vue';
import type {ElTable} from 'element-plus';
import {Plus} from '@element-plus/icons-vue';
import type {TagProps} from 'element-plus';
import {reactive} from 'vue';
import dayjs from 'dayjs';

enum MapStatusEnum {
  QUEUE = 0,
  IN_PROGRESS = 1,
  COMPLETED = 2,
  FAILED = 3
}

interface FileItem {
  date: number;
  name: string;
  status: MapStatusEnum;
  progress: number;
}

interface MapStatusItem {
  type: TagProps['type'];
  text: string;
}

type MapStatus = Map<number, MapStatusItem>;

const mapStatus: MapStatus = new Map([
  [MapStatusEnum.QUEUE, {type: 'info', text: '排队中'}],
  [MapStatusEnum.IN_PROGRESS, {type: 'warning', text: '进行中'}],
  [MapStatusEnum.COMPLETED, {type: 'success', text: '已完成'}],
  [MapStatusEnum.FAILED, {type: 'danger', text: '已失败'}]
]);

const statusArray = Array.from(mapStatus, ([value, {text: label}]) => ({label, value}));

type FileForm = {name: string; status: MapStatusEnum | undefined};

const fileForm: FileForm = reactive({
  name: '',
  status: undefined
});

const fileInput = ref<HTMLInputElement | null>(null);

const tableData = ref<FileItem[]>([]);

const currentPage = ref<number>(1);
const pageSize = ref<number>(5);

const total = computed<number>(() => tableData.value.length);

// 表中数据
const dataSource = computed<FileItem[]>(() => {
  // 第一页 0 ((currentPage.value - 1) *pageSize)  - 5 slice(0, 5) => 前五条
  // 第二页 5 ((2 - 1) *pageSize) - 10 slice(1, 10) => +五条
  // 第三页 10 ((3 - 1) *pageSize) - 15 slice(2, 10) => +五条

  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return tableData.value.slice(startIndex, endIndex);
});

const handleUploadFile = (): void => {
  fileInput.value!.click();
};

const handleFileInputChange = (event: Event): void => {
  const target = event.target as HTMLInputElement;
  const files: FileList | null = target.files;
  if (!files) {
    return;
  }

  const fileArray: FileItem[] = Array.from(files, (file: File) => {
    return {date: Date.now(), name: file.name, status: MapStatusEnum.QUEUE, progress: 0};
  });

  // 解决选择相同的文件
  // 没有触发change事件
  target.value = '';

  console.log(fileArray);

  tableData.value.push(...fileArray);
};

const handleSizeChange = (val: number): void => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number): void => {
  console.log(`current page: ${val}`);
};

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<FileItem[]>([]);
// eslint-disable-next-line
const toggleSelection = (rows?: FileItem[]): void => {
  if (rows) {
    rows.forEach((row) => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      multipleTableRef.value!.toggleRowSelection(row, false);
    });
  } else {
    multipleTableRef.value!.clearSelection();
  }
};
const handleSelectionChange = (val: FileItem[]): void => {
  multipleSelection.value = val;
};

// import {getTodos, type TodoItem} from '@/apis/todos';
// import {useRouter} from 'vue-router';
// import {ref, onMounted} from 'vue';

// const router = useRouter();
// function onClickLog() {
//   router.push({path: `/log/${Math.random().toString().slice(2)}`});
// }

// const todos = ref<TodoItem[]>([]);

// onMounted(() => {
//   getTodos().then((response: {data: TodoItem[]}) => {
//     console.log('data', response.data);
//     todos.value = response.data;
//   });
// });
</script>

<style lang="scss" scoped>
.file-list-container {
  // height: 100vw;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
}
.file-form {
  padding: 24px 24px 20px 24px;
  box-sizing: border-box;
}

.file-operations {
  margin: 20px 24px 10px 24px;
}

.file-table {
  padding: 0px 24px;
}

.file-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.file-name {
  white-space: nowrap; // 阻止换行
  overflow: hidden; // 超出部分隐藏
  text-overflow: ellipsis; // 使用省略号表示超出部分
}

.file-pagination {
  margin-bottom: 24px;
}
</style>
